package src.java.medium;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @author 袁敏
 * @className Solution103
 * @date 2024/7/27
 * @description TODO
 */
public class Solution103 {
    List<List<Integer>> res = new ArrayList<>();

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1, new TreeNode(2, new TreeNode(4), null), new TreeNode(3, null, new TreeNode(5)));

        Solution103 solution103 = new Solution103();
        List<List<Integer>> res = solution103.zigzagLevelOrder(root);
    }

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        if (root == null) return res;
        Deque<TreeNode> deque = new LinkedList<>();
        deque.add(root);
        int level = 0;
        while (!deque.isEmpty()) {
            int size = deque.size();
            List<Integer> levelList = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                if (level % 2 == 0) {
                    TreeNode treeNode = deque.pollFirst();
                    levelList.add(treeNode.val);
                    if (treeNode.left != null) deque.addLast(treeNode.left);
                    if (treeNode.right != null) deque.addLast(treeNode.right);
                } else {
                    TreeNode treeNode = deque.pollLast();
                    levelList.add(treeNode.val);
                    if (treeNode.right != null) deque.addFirst(treeNode.right);
                    if (treeNode.left != null) deque.addFirst(treeNode.left);
                }
            }
            res.add(levelList);
            level++;
        }
        return res;
    }
}
